package com.lingyu.jsjx.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lingyu.jsjx.domain.IspBaseEntity;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.BaseEntity;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class IspMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        fillBaseFields(metaObject, true); // 插入时填充
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        fillBaseFields(metaObject, false); // 更新时填充
    }

    private void fillBaseFields(MetaObject metaObject, boolean isInsert) {
        if (metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity CommonBaseEntity = (BaseEntity) metaObject.getOriginalObject();
            Date current = DateUtils.getNowDate();

            // 填充时间字段
            if (isInsert && CommonBaseEntity.getCreateTime() == null) {
                CommonBaseEntity.setCreateTime(current); // 创建时间
            }
            if (CommonBaseEntity.getUpdateTime() == null) {
                CommonBaseEntity.setUpdateTime(current); // 更新时间
            }

            // 填充用户信息（从请求中获取）
            String userId = String.valueOf(SecurityUtils.getUserId()); // 用户ID
            String userName = SecurityUtils.getUsername(); // 昵称

            if (userId != null) {
                if (isInsert && CommonBaseEntity.getCreateBy() == null) {
                    CommonBaseEntity.setCreateBy(userId); // 创建人编码
                }
                if (CommonBaseEntity.getUpdateBy() == null) {
                    CommonBaseEntity.setUpdateBy(userId); // 更新人编码
                }
            }

            if (userName != null) {
                if (isInsert && CommonBaseEntity.getCreateByName() == null) {
                    CommonBaseEntity.setCreateByName(userName); // 创建人昵称（核心）
                }
                if (CommonBaseEntity.getUpdateByName() == null) {
                    CommonBaseEntity.setUpdateByName(userName); // 更新人昵称（核心）
                }
            }
        }
    }
}